/**
 * data中url定义 add为新增接口  edit为编辑接口
 * 表单组件ref定义为ruleForm
 * formkeys定义为表单字段
 */
import pick from 'lodash.pick'
import { httpAction } from '@/services/manage'
export default {
  data() {
    return {
      title: '新增',
      visible: false,
      model: {},
      form: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      disableSubmit: false,
      fullscreen: false,
      switchFullscreen: true,
      formkeys: [],
      editType: ''
    }
  },
  computed: {
    vxeTableOption() {
      const defaultToolbarConfig = {
        buttons: [
          { buttonRender: { name: 'VxeToolbarAdd', events: { click: this.handleAdd }, disabled: this.disableSubmit }},
          { buttonRender: { name: 'VxeToolbarDel', events: { click: this.batchDel }, disabled: this.disableSubmit }}
        ],
        perfect: true
      }
      /*
      *customTableToolbar为页面需要自定义的toolbar配置
      *也可以直接在页面组件使用时直接定义属性覆盖该配置
      */
      const toolbarConfig = Object.assign({ }, defaultToolbarConfig, this.customTableToolbar)
      return {
        id: 'id',
        border: true,
        resizable: true,
        'keep-source': true,
        // 'min-height': 200,
        'edit-config': this.disableSubmit ? false : { trigger: 'click', mode: 'cell', showStatus: true, autoClear: false },
        'checkbox-config': { checkMethod: () => !this.disableSubmit },
        toolbarConfig: toolbarConfig
      }
    },
    modalOption() {
      return {
        title: this.title,
        destroyOnClose: true,
        width: '80%',
        visible: this.visible,
        'fullscreen.sync': this.fullscreen,
        'switchFullscreen': this.switchFullscreen,
        confirmLoading: this.confirmLoading,
        cancelText: '关闭',
        afterClose: this.afterClose
      }
    }
  },
  methods: {
    async handleOk() {
      try {
        // 校验主表单及子表
        await this.getAllValidate()
        // 提交前事件处理 需要阻止继续提交 需要返回异步Promise new Promise((resolve, reject)=>{ reject() })
        if (typeof this.submitBefore === 'function') await this.submitBefore()
        this.confirmLoading = true
        const formData = this.classifyIntoFormData ? this.classifyIntoFormData() : Object.assign(this.model, this.form)
        const res = await this.request(formData)
        this.confirmLoading = false
        if (res.success) {
          // 提交后事件处理
          typeof this.submitAfter === 'function' ? this.submitAfter(res) : this.defaultCallback(res)
        } else {
          this.$message.warning(res.message)
        }
        // 提交后事件处理
        // if (typeof this.submitAfter === 'function') await this.submitAfter()
      } catch (error) {
        console.log(error)
      }
    },
    defaultCallback(res) {
      this.$message.success(res.message)
      this.$emit('ok')
      this.close()
    },
    getAllValidate() {
      let values = []
      if ((this.refKeys instanceof Array)) {
        values = this.refKeys.map(key => {
          const target = this.$refs[key]
          return target.$vnode.tag.indexOf('VxeGrid') >= 0 ? this.tableValidate(target) : target.validate()
        })
      }
      values.push(this.$refs.ruleForm.validate())
      return Promise.all(values)
    },
    tableValidate(target) { // 修改vxetable校验返回值与form一致
      return new Promise((resolve, reject) => {
        target.validate(true, err => {
          if (err) {
            reject(err)
          }
          resolve(true)
        })
      })
    },
    handleCancel() {
      this.close()
    },
    add(data) {
      this.editType = 'add'
      if (typeof this.addBefore === 'function') this.addBefore(data)
      this.title = '新增'
      this.visible = true
      if (typeof this.addAfter === 'function') this.addAfter(data)
    },
    edit(data) {
      this.editType = 'edit'
      if (typeof this.addBefore === 'function') this.editBefore(data)
      this.title = '编辑'
      this.model = Object.assign({}, data)
      this.visible = true
      this.form = this.formkeys && this.formkeys.length > 0 ? pick(this.model, [...this.formkeys]) : Object.assign({}, data)
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    close() {
      this.$emit('close')
      this.model = {}
      this.form = {}
      this.$refs.ruleForm.resetFields()
      this.visible = false
      this.disableSubmit = false
    },
    request(formData) {
      let url = this.url.add; let method = 'post'
      if (this.editType === 'edit') {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      return httpAction(url, formData, method)
      // .then((res) => {
      //   if (res.success) {
      //     this.$message.success(res.message)
      //     this.$emit('ok')
      //     !this.callback ? this.close() : this.callback(res)
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // }).finally(() => {
      //   this.confirmLoading = false
      // })
    },
    handleAdd(key, target) {
      target.insert().then(({ row }) => {
        target.setActiveRow(row)
      })
    },
    batchDel(key, target) {
      target.removeCheckboxRow()
    },
    createdVxeTableData(tableKey, dataSource) { // 解决vxe-table数据无列字段时,编辑表格数据无法双向绑定bug
      const $table = this.$refs[tableKey]
      $table.createData(dataSource).then(list => {
        $table.loadData(list)
      })
    },
    afterClose() {
      Object.assign(this.$data, this.$options.data())
    }
  }
}

